<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <input type="button" value="点击按钮" id="btn">
    <div class="box" id="box">
        <span>我是span</span>
        <p>我是p</p>
        <span>我是span</span>
        <p>我是p</p>
    </div>

    <script>
        var btnObj = document.getElementById('btn')
        var pObj = document.getElementsByTagName('p')
        var box = document.getElementById('box')
        var nodes = box.childNodes
        console.log(nodes)

        btnObj.onclick = function () {
            // for(var i=0;i<pObj.length;i++){
            //     pObj[i].style.backgroundColor = 'red'
            // }
            //利用节点来给p设置背景色
            for (var i = 0; i < nodes.length; i++) {
                if (nodes[i].nodeName == !"P") {
                    nodes[i].style.backgroundColor = 'red'
                }else if(nodes[i].nodeName == 'SPAN'){
                    nodes[i].style.backgroundColor = 'yellow'
                }
            }

        }
    </script>
</body>

</html>